package com.android.antelopeapp.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.antelopeapp.R;
import com.android.antelopeapp.common.GlobalResource;
import com.android.antelopeapp.common.ImageTool;
import com.android.antelopeapp.view.BeautyPic.ImageTagBox;
import com.android.antelopeapp.view.BeautyPic.TagableImage;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by phk on 2014/12/21.
 * 给图片添加标签页面，
 * 首先会调用ChoosePicActivity选择图片，
 * 然后给图片添加标签并上传到服务器
 */
public class TagImageActivity extends BaseActivity{
    public static final String TAG = "TagImageActivity";
    public static final String IMAGE_TAGS = "ImageTags";
    /**按钮框下拉的高度，需要与anim/drop_down中的高度一致*/
    public static final int DROP_HEIGHT=150;
    private final int mTagCats[] = {R.string.imgtag_1, R.string.imgtag_2, R.string.imgtag_3};
    /**
     * 搜索框容器
     */
    private ViewGroup mSearchContainer;
    /**
     * 输入搜索内容控件*
     */
    private EditText mSearchText;
    /**
     * 标题
     */
    private TextView mTitle;
    /**
     * 下一步*
     */
    private TextView mNextBtn;
    /**
     * 取消搜索*
     */
    private TextView mSearchCancel;
    /**
     * 可添加标签的图片控件
     */
    private TagableImage mTagableImage;
    /**按钮栏*/
    private ViewGroup mControlBtns;
    /**
     * 按钮栏中的按钮，实际上是以textview的形式存在的*
     */
    private List<TextView> mBtnList;
    /**
     * 提示框*
     */
    private ListView mSuggestionList;
    private Animation myAnimation_Translate_Down;
    private Animation   myAnimation_Translate_Up;
    private int mStep;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(null);
        getSupportActionBar().setLogo(null);
        //getSupportActionBar().setTitle(R.string.tagimage);
        //标题
        mTitle = (TextView) this.findViewById(R.id.tagimage_title);
        //下一步
        mNextBtn = (TextView) this.findViewById(R.id.imagetag_search_next);
        //初始化搜索组件
        bindSearchCom();
        //tag容器
        mTagableImage = (TagableImage) this.findViewById(R.id.view_tagable_image);
        initTagableImage();

        mStep = 0;
        //按钮栏
        mControlBtns = (ViewGroup)this.findViewById(R.id.show_control_btns);
        //所有按钮
        mBtnList = new ArrayList<>();
        for(int i=0;i<mControlBtns.getChildCount();i++) {
            final int j = i;
            mBtnList.add((TextView) mControlBtns.getChildAt(i));
            mControlBtns.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v(TAG, "onClick controlbtn " + j);
                    //设置标签类型
                    ImageTagBox lastBox = mTagableImage.getLastTagBox();
                    if (lastBox != null) {
                        lastBox.getmImgTag().setmCatName(TagImageActivity.this.getString(mTagCats[j]));
                        lastBox.updateTag();
                    }
                    goNextStep();
                }
            });
        }

        //滚动动画
        myAnimation_Translate_Down = AnimationUtils.loadAnimation(this,R.anim.drop_down);
        myAnimation_Translate_Down.setDuration(1000);
        myAnimation_Translate_Down.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mControlBtns.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        myAnimation_Translate_Up =  AnimationUtils.loadAnimation(this,R.anim.pull_up);
        myAnimation_Translate_Up.setDuration(1000);
        myAnimation_Translate_Up.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mControlBtns.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        /**在编辑模式下，点击空白处会添加标签控件
         * 在添加标签的同时，显示标签类型按钮
         * */
        mTagableImage.setOnAddTagBoxListener(new TagableImage.OnAddTagBoxListener() {
            @Override
            public void onAddTagBox(ImageTagBox tagBox) {
                Log.v(TAG, "onAddTagBox ");
                goNextStep();
            }
        });
        /**
         * 点击下一步，提交数据到服务器
         * */
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gson gson = new Gson();
                Log.v(TAG, "tags: " + (gson.toJson(mTagableImage.getmTags())));

                //todo 需要删除 这里为测试
                Intent intent = new Intent(null, Uri.parse(gson.toJson(mTagableImage.getmTags())));
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    /**
     * 初始化标签图片容器
     * 显示传递过来的图片
     */
    private void initTagableImage() {
        //如果包含图片路径参数，则设置图片
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null && bundle.getString(UploadBPicActivity.PIC_PATH) != null) {
            String imgpath = bundle.getString(UploadBPicActivity.PIC_PATH);
            mTagableImage.setImg(
                    ImageTool.decodeSampledBitmapFromFile(imgpath,
                            mTagableImage.getmImage().getWidth(),
                            mTagableImage.getmImage().getHeight())
            );
        } else if (this.getIntent().getExtras() != null && this.getIntent().getExtras().get(UploadBPicActivity.PIC_BITMAP) != null) {
            //如果包含图片参数，则设置图片
            mTagableImage.setImg((android.graphics.Bitmap) this.getIntent().getExtras().get(UploadBPicActivity.PIC_BITMAP));
        } else if (GlobalResource.getInstance().getmBitmap(GlobalResource.TAGED_IMG) != null) {
            mTagableImage.setImg(GlobalResource.getInstance().getmBitmap(GlobalResource.TAGED_IMG));
        }
        //设置为编辑模式
        mTagableImage.setmInteractModel(TagableImage.EDIT_MODE);

    }

    /**
     * 绑定搜索组件
     */
    private void bindSearchCom() {
        //上方的输入容器
        mSearchContainer = (ViewGroup) this.findViewById(R.id.imagetag_search_bar);
        //输入框
        mSearchText = (EditText) this.findViewById(R.id.imagetag_search_edittext);
        //取消搜索
        mSearchCancel = (TextView) this.findViewById(R.id.imagetag_search_cancel);
        //提示框
        mSuggestionList = (ListView) this.findViewById(R.id.imagetag_search_suggestion);
        //mSuggestionList.setSelector(null);


        mSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setSuggestion(s.toString());
            }
        });

    }

    /**
     * 根据当前进度控制页面
     */
    private void goNextStep() {
        switch (mStep) {
            case 0:
                //第一阶段为点击空白处添加标签激活
                //滚动按钮栏，切换到可见
                mControlBtns.startAnimation(myAnimation_Translate_Down);
                //将标签控件设置为不可触
                mTagableImage.setmIsTouchable(false);
                break;
            case 1:
                //第二阶段为点击标签类型激活

                //隐藏标签按钮
                mControlBtns.startAnimation(myAnimation_Translate_Up);
                //显示搜索栏
                showSearchBar();
                break;
            case 2:
                //第三阶段为确认输入标签内容激活

                //隐藏搜索栏
                hideSearchBar();
                //恢复控件为可触摸
                mTagableImage.setmIsTouchable(true);
                break;
        }
        mStep++;
        //如果已经完成一个周期，则重置计数
        mStep = mStep == 3 ? 0 : mStep;
    }

    private void goPreStep() {
        switch (mStep) {
            case 1:
                //当前处于第二阶段，按钮栏为可见，搜索栏不可见

                //滚动按钮栏，切换为为不可见
                mControlBtns.startAnimation(myAnimation_Translate_Up);
                //将标签控件设置为可触
                mTagableImage.setmIsTouchable(true);
                //删除第一阶段刚添加的标签
                mTagableImage.delLastImgTag();
                break;
            case 2:
                //当前处于第三阶段，搜索栏为可见，按钮栏为不可见

                //隐藏搜索栏
                hideSearchBar();
                //显示按钮栏
                //滚动按钮栏，切换为为不可见
                mControlBtns.startAnimation(myAnimation_Translate_Down);
                break;
        }
        if (mStep != 0) {
            mStep--;
        }
    }

    /**
     * 动态改变suggestion
     */
    private void setSuggestion(final String text) {
        final String[] strs = {"添加标签:" + text};
        mSuggestionList.setAdapter(new ArrayAdapter<String>(this, R.layout.view_dark_textview, strs));
        mSuggestionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (text == null || text.length() == 0) {
                    toast("输入不能为空");
                } else {
                    if (position == 0) {
                        completeTag(text);
                    } else {
                        completeTag(strs[position]);
                    }
                }
            }
        });
    }

    /**
     * 完成添加tag标签
     */
    private void completeTag(String tagText) {
        ImageTagBox lastBox = mTagableImage.getLastTagBox();
        if (lastBox != null) {
            lastBox.getmImgTag().setmText(tagText);
            lastBox.updateTag();
        }
        goNextStep();
    }

    @Override
    protected void setOverflowShowingAlways() {
        //do nothing
        //super.setOverflowShowingAlways();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_tagimage;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            goPreStep();
            return true;
        } else if(keyCode == KeyEvent.KEYCODE_MENU) {
            // 监控菜单键
            Toast.makeText(TagImageActivity.this, "Menu", Toast.LENGTH_SHORT).show();
            return false;
        }
        return false;
    }

    /**
     * 显示搜索框
     */
    private void showSearchBar() {
        //将整个搜索框显示为可见
        mSearchContainer.setVisibility(View.VISIBLE);
        //激活推荐列表
        mSuggestionList.setVisibility(View.VISIBLE);
        //激活输入框
        mSearchText.requestFocus();
        //清空输入框
        mSearchText.setText("");
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mSearchText, InputMethodManager.SHOW_IMPLICIT);
        //隐藏标题
        mTitle.setVisibility(View.GONE);
        //隐藏下一步按钮
        mNextBtn.setVisibility(View.GONE);
    }

    /**
     * 隐藏搜索框
     */
    private void hideSearchBar() {
        //关闭软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
        //隐藏搜索框
        mSearchContainer.setVisibility(View.GONE);
        //隐藏推荐列表
        mSuggestionList.setVisibility(View.GONE);
        //显示标题
        mTitle.setVisibility(View.VISIBLE);
        //显示下一步
        mNextBtn.setVisibility(View.VISIBLE);
    }

    private void triggleSearchBar() {
        if (mSearchContainer.getVisibility() == View.INVISIBLE) {
            showSearchBar();
        } else {
            hideSearchBar();
        }
    }
}
